import csv
import re

def extract_question_type(question_content):
    """从题目内容中提取题型标记"""
    if re.search(r'\[单选\]', question_content):
        return "single"
    elif re.search(r'\[多选\]', question_content):
        return "multiple"
    elif re.search(r'\(single\)', question_content, re.IGNORECASE):
        return "single"
    elif re.search(r'\(multiple\)', question_content, re.IGNORECASE):
        return "multiple"
    else:
        print("警告：未检测到明确题型标记，默认按单选处理")
        return "single"


def is_question_line(line):
    """判断是否是题目行"""
    return re.search(r'(?:\d+、\s*)?\[.*?\]', line) is not None


def is_option_line(line):
    """判断是否是选项行"""
    return re.search(r'^[A-E]、|^选项[A-E]|^-\s*[A-E]', line.strip()) is not None


def is_answer_line(line):
    """判断是否是答案行"""
    return re.search(r'正确答案[:：]', line) is not None


def is_analysis_line(line):
    """判断是否是解析行"""
    return re.search(r'解析[:：]', line) is not None


def process_question_block(block):
    """处理题目块，提取题目、选项、答案和解析"""
    data = {
        "题目": "", "选项A": "", "选项B": "", "选项C": "", 
        "选项D": "", "选项E": "", "正确答案(字母，如AB)": "", 
        "解析": "", "题型(single/multiple)": "single"
    }
    
    # 提取题目内容
    question_lines = []
    option_lines = []
    answer_line = ""
    analysis_lines = []
    
    current_section = "question"
    
    for line in block.split('\n'):
        line = line.strip()
        if not line:
            continue
        
        if is_option_line(line) and current_section != "analysis":
            current_section = "option"
            option_lines.append(line)
        elif is_answer_line(line) and current_section != "analysis":
            current_section = "answer"
            answer_line = line
        elif is_analysis_line(line):
            current_section = "analysis"
            analysis_lines.append(line.replace("解析：", "").replace("解析:", ""))
        elif current_section == "analysis":
            analysis_lines.append(line)
        elif current_section == "answer":
            # 答案可能有多行
            answer_line += line
        elif current_section == "option":
            # 选项可能有多行
            option_lines[-1] += line
        else:
            question_lines.append(line)
    
    # 拼接题目
    data["题目"] = ' '.join(question_lines)
    
    # 提取选项
    for line in option_lines:
        match = re.match(r'([A-E])、|选项([A-E])|^-\s*([A-E])', line)
        if match:
            opt = match.group(1) or match.group(2) or match.group(3)
            content = re.sub(r'^[A-E]、|^选项[A-E]|^-\s*[A-E]', '', line).strip()
            # 移除开头可能存在的冒号
            content = re.sub(r'^[:：]\s*', '', content)
            data[f"选项{opt}"] = content
    
    # 提取答案
    answer_match = re.search(r'正确答案[:：]\s*([A-Z,]+)', answer_line)
    if answer_match:
        data["正确答案(字母，如AB)"] = answer_match.group(1).strip()
    
    # 提取解析
    data["解析"] = ' '.join(analysis_lines).strip()
    
    # 确定题型
    data["题型(single/multiple)"] = extract_question_type(data["题目"])
    
    return data

def txt_to_csv(txt_file_path, csv_file_path):
    """处理多题目TXT文件并转换为CSV"""
    try:
        all_questions = []
        current_question = []
        question_count = 0
        
        # 逐行读取文件
        with open(txt_file_path, 'r', encoding='utf-8') as txt_file:
            lines = txt_file.readlines()
            
            for i, line in enumerate(lines):
                stripped_line = line.strip()
                
                # 跳过空行
                if not stripped_line:
                    continue
                
                # 检查是否是新题目的开始
                if is_question_line(stripped_line):
                    # 如果当前已有题目，处理上一题
                    if current_question:
                        question_count += 1
                        question_block = '\n'.join(current_question)
                        try:
                            question_data = process_question_block(question_block)
                            all_questions.append(question_data)
                            print(f"解析第{question_count}题成功：")
                            print(f"题目: {question_data['题目'][:50]}...")
                            print(f"选项A: {question_data['选项A'][:30]}...")
                            print("----")
                        except Exception as e:
                            print(f"解析第{question_count}题失败：{str(e)}")
                            print(f"失败的题目块内容：{question_block[:200]}...")
                        # 重置当前题目
                        current_question = []
                    # 添加新题目行
                    current_question.append(stripped_line)
                else:
                    # 添加到当前题目
                    current_question.append(stripped_line)
            
            # 处理最后一题
            if current_question:
                question_count += 1
                question_block = '\n'.join(current_question)
                try:
                    question_data = process_question_block(question_block)
                    all_questions.append(question_data)
                    print(f"解析第{question_count}题成功：")
                    print(f"题目: {question_data['题目'][:50]}...")
                    print(f"选项A: {question_data['选项A'][:30]}...")
                    print("----")
                except Exception as e:
                    print(f"解析第{question_count}题失败：{str(e)}")
                    print(f"失败的题目块内容：{question_block[:200]}...")
        
        # 写入CSV
        csv_fields = [
            "题目", "选项A", "选项B", "选项C", "选项D", 
            "选项E", "正确答案(字母，如AB)", "解析", "题型(single/multiple)"
        ]
        
        with open(csv_file_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=csv_fields)
            writer.writeheader()
            writer.writerows(all_questions)
        
        print(f"\n转换完成！共成功解析{len(all_questions)}题，已保存至 {csv_file_path}")
        
    except FileNotFoundError:
        print(f"错误：找不到文件 {txt_file_path}")
    except Exception as e:
        print(f"处理过程出错：{str(e)}")

if __name__ == "__main__":
    # 配置文件路径
    INPUT_TXT = "multiple_questions.txt"    # 包含多题目的TXT文件
    OUTPUT_CSV = "multiple_questions.csv"   # 输出的CSV文件
    
    # 执行转换
    txt_to_csv(INPUT_TXT, OUTPUT_CSV)
